package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.logging.SimpleFormatter;

@Service
public class  FileServiceImpl implements FileService {

    @Autowired
    private MinioProperties minioProperties;
    @Autowired
    private MinioClient minioClient;
    @Override
    public String upload(MultipartFile file) {
        //1.创建bucket
        createBucket();

        //2.上传文件
        String fileName = putObject(file);



        return fileName;
    }

    public String putObject(MultipartFile file){
        //2.上传文件
        String bucketName = minioProperties.getBucketName();
        //2.1解决重名问题
        //2.1.1获取文件后缀名+UUID
        String fileName = file.getOriginalFilename();
        String uuid = java.util.UUID.randomUUID().toString().replace("-", "");

        //2.1.2获取时间目录
        String dirPath =new  SimpleDateFormat("/yyyy/MM/").format(new Date());
        fileName =dirPath+ uuid + fileName.substring(fileName.lastIndexOf("."));


        //3.指定文件类型
        String contentType = file.getContentType();
        try {
            //1桶 2文件对象 3。文件类型 4.文件流
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .contentType(contentType)
                    .stream(file.getInputStream(),file.getSize(),-1)
                    .build();
            minioClient.putObject(putObjectArgs);
        }catch (Exception e){
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return minioProperties.getEndpoint()+"/"+bucketName+fileName;
    }

    public void createBucket(){
        String bucketName = minioProperties.getBucketName();

        try {
            //判断 buckget为空时 创建一个新的bucket
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();
                minioClient.makeBucket(makeBucketArgs);
                //设置自定义策略
                //%s动态给这个位置赋值 通过formatted方法
                String config = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(bucketName);
                SetBucketPolicyArgs setBucketPolicyArgs =
                        SetBucketPolicyArgs.builder().bucket(bucketName).config(config).build();
                minioClient.setBucketPolicy(setBucketPolicyArgs);
            }
        } catch (Exception e) {
//            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
